/*
 * Copyright (c) 2016. For Intelligent Group.
 */
package com.intelligent.ispc.client.core.controller;

import com.google.common.collect.Maps;
import com.intelligent.ispc.client.core.view.global.MainStateBar;
import com.intelligent.ispc.client.core.view.global.MainTopMenuBar;
import com.intelligent.ispc.client.utils.ApplicationBeanUtils;
import com.intelligent.ispc.client.utils.ResourceMessages;
import com.intelligent.ispc.client.utils.SystemConfigUtils;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.common.utils.ResourceBundleUtils;
import com.intelligent.ispc.core.dto.UserDto;
import com.intelligent.ispc.core.entity.Role;
import com.intelligent.ispc.core.service.SecurityService;
import com.intelligent.ispc.core.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter on 2016/7/11.
 */
@Component
public class LoginController {
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SecurityService securityService;

    @Autowired
    private SystemService systemService;

    public void login(String username, String password) {

        logger.debug("Login with username:[{0}]", username);

        UserDto userDto = securityService.findByLoginName(username);
        Map<String, UserDto> userDtoMap = new HashMap<>();
        userDtoMap.put("user", userDto);
        ResourceMessages.userMap = userDtoMap;
        if (!userDto.getPassword().equals(password)) {
            throw new ApplicationException(ExceptionMessages.ERR_15007, ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_OBJECT_INVALID));
        }
        List<Role> roleList = userDto.getRoles();
        Map<Long, String> result = Maps.newHashMap();
        for (Role role : roleList) {
            result.put(role.getId(), role.getName());
        }

        if (!result.containsValue("admin")) {
            ApplicationBeanUtils.getBean(MainTopMenuBar.class).remove();
        } else {
            ApplicationBeanUtils.getBean(MainTopMenuBar.class).showvisiable();
        }
        ApplicationBeanUtils.getBean(MainStateBar.class).setUser(username);

        List<Integer> digits = systemService.findSpcAndGrrDigit();
        SystemConfigUtils.getInstance().setSpcDigit(digits.get(0));
        SystemConfigUtils.getInstance().setGrrDigit(digits.get(1));
    }
}


